package com.xiaotu.spider.qq.pageprocessor;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.TVProcessDataModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.KeywordEncode;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.TVProcessUtils;
import com.xiaotu.spider.APageProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;

import java.util.Arrays;
import java.util.Map;

/**
 * 腾讯视频 电视剧，网剧，网大 播放量
 */
@Component("QQPlayCountPageProcessor")
public class QQPlayCountPageProcessor extends APageProcessor {

    @Override
    protected Request getStartRequest(JSONObject target) {
        return new Request("http://s.video.qq.com/search?comment=1&stype=0"
                + "&plat=2&otype=json&query="
                + KeywordEncode.encode(target.getString("tvName"))
                + "&pver=0&tabid=0&sort=0&cur=0"
                + "&num=0&start=0&end=20&stag=txt.historyword");
    }

    @Override
    public void process(Page page) {
        Map<String, Object> tvMap = page.getRequest().getExtras();
        switch (this.getPageDataType(page)) {
            case Constants.PageDataType.SEARCH_LIST:
                this.searchListProcess(page, tvMap);
                break;
            case Constants.PageDataType.TV_RECORD:
                this.tvProcess(page, tvMap);
                break;
            default:
                break;
        }
    }

    private void tvProcess(Page page, Map<String, Object> tvMap) {
        String totalPlayCount = page.getHtml().xpath("//em[@id='mod_cover_playnum']/text()").get();
        totalPlayCount = totalPlayCount.replace(".0", "");
        if (StringUtils.isEmpty(totalPlayCount))
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        page.putField(TVProcessDataModel.class.getName(), new TVProcessDataModel(tvMap.get("tvid") + "", tvMap.get("tvName") + "",
                Constants.SiteName.QQTV, totalPlayCount, null, null));
    }

    private void searchListProcess(Page page, Map<String, Object> tvMap) {
        String searchList = page.getRawText();
        if (StringUtils.isEmpty(searchList))
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        searchList = searchList.replace("QZOutputJson=", StringUtils.EMPTY);
        searchList = searchList.substring(0, searchList.lastIndexOf(";"));
        JSONObject searchJson = JSONObject.fromObject(searchList);
        if (searchJson == null || searchJson.isEmpty()
                || !searchJson.has("list"))
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        JSONArray array = searchJson.getJSONArray("list");
        if (null == array || array.size() == 0)
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);

        boolean matched = false;
        for (int i = 0; i < array.size(); i++) {
            JSONObject item = array.getJSONObject(i);
            if (TVProcessUtils.tvMatched(tvMap, item.getString("title"), TVProcessUtils.getTVType
                            (item.getString("BC")), Arrays.asList(item.getString("BM").split(";")),
                    Arrays.asList(item.getString("BD").split(";"))) && "qq".equals(item.getString
                    ("PLNAME"))) {
                if (item.getString("imgtag").contains("片花") || item.getString("imgtag").contains("预告")) { // 片花或预告片
                    continue;
                }
                matched = true;
                //添加详情页获取累计播放量
                PageUtils.addTargetRequest(page, item.getString("AW"), tvMap);
                break;
            }
        }
        if (!matched)
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    }


    @Override
    public String getSpiderType() {
        return Constants.SpiderTaskType.TV_QQTV;
    }

    @Override
    public String getPageDataType(Page page) {
        String url = page.getUrl().toString();
        if (url.contains("http://s.video.qq.com/search?comment=1&stype=0"))
            return Constants.PageDataType.SEARCH_LIST;
        else if (url.contains("v.qq.com/x/cover"))
            return Constants.PageDataType.TV_RECORD;
        return "";
    }

}
